package com.yueya.auth.utils;

import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.SecretKey;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class KeysUtil {

    public static Map<String,String> createKeyPairs(SignatureAlgorithm sgn) {
        KeyPair pair = Keys.keyPairFor(sgn);
        String publickeys = Base64.encodeBase64String(pair.getPublic().getEncoded());
        String privatekeys = Base64.encodeBase64String(pair.getPrivate().getEncoded());
        Map<String,String> pairMap = new HashMap<>(2);
        pairMap.put("public",publickeys);
        pairMap.put("private",privatekeys);
        return pairMap;
    }

    public static Key getPrivateKeyFromString(String base64String,SignatureAlgorithm sgn)
            throws InvalidKeySpecException, NoSuchAlgorithmException {
        byte[] bt = Base64.decodeBase64(base64String);
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bt);
        KeyFactory keyFactory = KeyFactory.getInstance(sgn.getFamilyName());
        return keyFactory.generatePrivate(privateKeySpec);
    }

    public static Key getPublicKeyFromString(String base64String, SignatureAlgorithm sgn)
            throws InvalidKeySpecException, NoSuchAlgorithmException {
        byte[] bt = Base64.decodeBase64(base64String);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bt);
        KeyFactory keyFactory = KeyFactory.getInstance(sgn.getFamilyName());
        return keyFactory.generatePublic(publicKeySpec);
    }

    public static Key getSecretKey(String base64String, SignatureAlgorithm sgn) {
        byte[] bt = Base64.decodeBase64(base64String);
        SecretKey key = Keys.hmacShaKeyFor(bt);
        return key;
    }

    public static String generteHS256Key(){
        byte [] bytes = Keys.secretKeyFor(SignatureAlgorithm.HS256).getEncoded();
        return Base64.encodeBase64String(bytes);
    }

    public static void main(String[] args) {
        createKeyPairs(SignatureAlgorithm.RS256)
        .forEach((k,v) -> System.out.println(k+":"+v));
        System.out.println(generteHS256Key());
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-","");
    }
}
